package com.gz.rocketmq.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.CountDownLatch2;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

public class AsynProducer {

    public static void main(String[] args) throws InterruptedException {


        DefaultMQProducer producer = new DefaultMQProducer("rocketmq02");
        int messageCount = 5;
        // 根据消息数量实例化倒计时计算器
        final CountDownLatch2 countDownLatch = new CountDownLatch2(messageCount);
        try {
            producer.setNamesrvAddr("192.168.36.128:9876");
            producer.start();
            producer.setRetryTimesWhenSendAsyncFailed(0);
            for (int i = 0; i < messageCount; i++) {
                Message message = new Message();
                message.setTopic("topic02");
                message.setTags("tag02");
                message.setBody((i + "-Hello02").getBytes());
                producer.send(message, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.println("成功！");
                        System.out.println(sendResult);
                    }
                    @Override
                    public void onException(Throwable throwable) {
                        System.out.println("错误！"+ throwable.getMessage());
                        throwable.printStackTrace();

                    }
                });
            }
        } catch (Exception e) {

        }

            countDownLatch.await(5, TimeUnit.SECONDS);
            producer.shutdown();


    }

}
